package com.example.springworkfront.controller;

import com.example.springworkfront.untils.WeixinUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * @ClassName weixin
 * @Author zhangwen
 * @Description 测试号接入
 * @Date 2019/12/16 15:39
 */
@RestController
@RequestMapping("/weixin")
public class Wxcontroller {
    @Autowired
    private WeixinUtils weixinservice;

    @GetMapping("/wx")
    public void wx(HttpServletRequest request, HttpServletResponse response){
        //获取微信服务器发来的参数，并将token、timestamp、nonce三个参数进行字典序排序
        //将三个参数字符串拼接成一个字符串进行sha1加密
        //开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        //check方法用来排序以及比较
        if (weixinservice.check(timestamp,nonce,signature)){
            PrintWriter out = null;
            try {
                out = response.getWriter();
                out.print(echostr);
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                out.flush();//刷新文件流
                out.close();//关闭文件流
            }
            System.out.println("接入成功");

        }
    }
}
